<template>
  <div class="explore">
    <el-menu mode="horizontal" default-active="explore">
      <el-menu-item index="explore">发现</el-menu-item>
      <el-menu-item index="publish" @click="checkLogin">发布</el-menu-item>
      <el-menu-item index="notifications" @click="checkLogin">通知</el-menu-item>
      <el-menu-item v-if="!authStore.token" index="login" @click="loginDialog.open()">登录</el-menu-item>
      <el-menu-item v-else index="user">{{ authStore.user?.username || '我' }}</el-menu-item>
      <el-input v-model="search" placeholder="搜索笔记" style="width: 200px;" @input="searchNotes" />
    </el-menu>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="全部" name="all" />
      <el-tab-pane label="美食" name="food" />
      <el-tab-pane label="彩妆" name="makeup" />
    </el-tabs>
    <div class="notes">
      <el-card v-for="note in notes" :key="note.id" class="note-card" @click="$router.push(`/notes/${note.id}`)">
        <img v-if="note.image" :src="`http://localhost:8000/storage/${note.image}`" alt="笔记图片" />
        <h3>{{ note.title }}</h3>
        <p>作者: {{ note.user?.username || '未知' }}</p>
      </el-card>
    </div>
    <LoginDialog ref="loginDialog" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { useAuthStore } from '../stores/auth';
import LoginDialog from '../components/LoginDialog.vue';

const router = useRouter();
const authStore = useAuthStore();
const loginDialog = ref(null);
const activeTab = ref('all');
const search = ref('');
const notes = ref([]);

const fetchNotes = async (searchQuery = '') => {
  try {
    const response = await axios.get('/api/notes', { params: { search: searchQuery } });
    notes.value = response.data.data;
  } catch (error) {
    console.error('获取笔记失败:', error);
  }
};

onMounted(() => fetchNotes());

const searchNotes = () => {
  fetchNotes(search.value);
};

const checkLogin = () => {
  if (!authStore.token) loginDialog.value.open();
  else router.push(event.currentTarget.getAttribute('index'));
};
</script>

<style scoped>
.explore { padding: 20px; }
.notes { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; }
.note-card img { width: 100%; height: 150px; object-fit: cover; }
</style>